package controller.servlets;

import dao.UserDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modle.User;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ChangePasswordServlet", value = "/changePassword")
public class ChangePasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String newPassword = request.getParameter("newPassword");
        //根据用户名更新数据库中的密码
        UserDao LDao = new UserDao();
        // 通过HttpServletRequest对象获取Session对象
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        String type = user.getRoletype();
        String uAcc = user.getUsername();

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(LDao.setPassword(type, uAcc, newPassword))
            out.print("{\"code\": 0, \"msg\": \"\"}");
        else
            out.print("{\"code\": -1, \"msg\": \"\"}");
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
